package io.ent.common.aspect;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import io.ent.common.annotation.SysLoginLog;
import io.ent.common.utils.HttpContextUtils;
import io.ent.common.utils.IPUtils;
import io.ent.modules.sys.entity.SysLoginLogEntity;
import io.ent.modules.sys.entity.SysUserEntity;
import io.ent.modules.sys.service.SysLoginLogService;

/**
 * 登录日志，切面处理类
 *
 * 
 */
@Aspect
@Component
public class SysLoginLogAspect {
	@Autowired
	private SysLoginLogService sysLoginLogService;
	//配置接入点
	@Pointcut("@annotation(io.ent.common.annotation.SysLoginLog)")
	public void logPointCut() { 
		
	}

	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		long beginTime = System.currentTimeMillis();
		//执行方法
		Object result = point.proceed();
		//执行时长(毫秒)
		long time = System.currentTimeMillis() - beginTime;

		//保存日志
		saveSysLoginLog(point, time);


		return result;
	}

	private void saveSysLoginLog(ProceedingJoinPoint joinPoint, long time) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		//状态
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletResponse response = requestAttributes.getResponse();
		System.out.println(">>>>>>>>>>>>>>>状态"+response.getStatus());
		int state = 0;
		if (response.getStatus()==200){
			state = 1;
		}
		SysLoginLogEntity sysLoginLog = new SysLoginLogEntity();
		sysLoginLog.setState(state);
		SysLoginLog sysLoginlog = method.getAnnotation(SysLoginLog.class);
		if(sysLoginlog != null){
			//注解上的描述
			sysLoginLog.setOperation(sysLoginlog.value());
		}

		//获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		//设置IP地址
		sysLoginLog.setIp(IPUtils.getIpAddr(request));
		//用户名
		String username = "游客";
		if (SecurityUtils.getSubject().getPrincipal()!=null){
			username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername();
		}
		sysLoginLog.setUsername(username);

		sysLoginLog.setTime(time);
		sysLoginLog.setCreateDate(new Date());
		//保存系统日志
		sysLoginLogService.save(sysLoginLog);


	}
}
